<?php 

namespace IMT\ServicesBundle\Controller;

use JMS\Serializer\SerializationContext;

use IMT\AccountBundle\Form\AccountGmailType;

use IMT\AccountBundle\Entity\AccountGmail;

use IMT\AccountBundle\Entity\AccountIMT;

use IMT\AccountBundle\Form\AccountIMTType;

use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\View\View;
use FOS\Rest\Util\Codes;

class AccountRestController extends Controller
{
	/**
	 * GET /account/{eventId}
	 *
	 * @param string $eventId
	 * @return Response
	 */
	public function getAccountAction($accountId)
	{			
		if(intval($accountId) == 0)
	    	throw new \InvalidArgumentException(400, 'L\'id est incorrect : '.$accountId);
	    
    	// Récupération de l'account
    	$repository = $this->getDoctrine()->getRepository('IMTAccountBundle:Account');
   		$account = $repository->findOneById($accountId);
   		
   		if (!$account)
   			throw new NotFoundHttpException('L\'$account ayant l\'id '.$accountId.' n\'existe pas');
   		
   		
   		// Vérification des droits d'acces
   		$securityContext = $this->get('security.context');
   		$user = $securityContext->getToken()->getUser();
   		
   		if($user->getId() != $account->getUser()->getId()){
   			throw new AccessDeniedException(403, 'Acces refuse pour '.$user->getUsername());
   		}

   		$context = new SerializationContext();
   		$context->setVersion('1.0');
   		$context->setGroups(array('account_details', 'event_list', 'user_list', 'contact_list'));
   			   		
		$view = View::create()
			->setStatusCode(200)
			->setData($account)
			->setSerializationContext($context);

		return $this->get('fos_rest.view_handler')->handle($view);
	}
	
	/**
	 * Creates a new Thread from the submitted data.
	 *
	 * @param Request $request The current request
	 *
	 * @return View
	 */
	public function postAccountAction(Request $request)
	{
		$idAccount = 0;
	
		$em = $this->getDoctrine()->getEntityManager();
		$viewHandler = $this->get('fos_rest.view_handler');
			
		if('POST' == $request->getMethod()){
			$idAccount = $request->request->get('account_idAccount');
			$type = $request->request->get('account_type');
			
			$validator = $this->get('validator');
			
			$account = null;
						
			$user = $this->get('security.context')->getToken()->getUser();
	
			switch($type){
				case 'imt':
					if($idAccount == 0){
						$account = new AccountIMT();
						$account->setUser($user);
					} else {
						$accounts = $em->getRepository('IMTAccountBundle:AccountIMT')->findBy(array(
							'id' => $idAccount,
							'user' => $user
						));
						
						$account = (isset($accounts[0])) ? $accounts[0] : null;
							
						if(!$account)
							throw $this->createNotFoundException('Le compte "'.$idAccount.'" n\'existe pas');
					}
										
					$account->setActive($request->request->get('account_active'));
					$account->setColor($request->request->get('account_color'));
					$account->setTitle($request->request->get('account_title'));					
					
					//return $viewHandler->handle($this->createErrorViewResponse($account));
					$errors = $validator->validate($account);
					
					if(count($errors) > 0){
						$return['errors'] = $errors;
					
						return $viewHandler->handle($this->createErrorViewResponse($return));
					} else {
						$em = $this->getDoctrine()->getEntityManager();
						$em->persist($account);
						$em->flush();
							
						$return['idAccount'] = $account->getId();
					
						return $viewHandler->handle($this->createSuccessViewResponse($return));
					}
					
					break;
				case 'gmail':
					if($idAccount == 0){
						$account = new AccountGmail();
						$account->setUser($user);
					} else {
						$accounts = $em->getRepository('IMTAccountBundle:AccountGmail')->findBy(array(
								'id' => $idAccount,
								'user' => $user
						));
					
						$account = (isset($accounts[0])) ? $accounts[0] : null;
							
						if(!$account)
							throw $this->createNotFoundException('Le compte "'.$idAccount.'" n\'existe pas');
					}
						
					$account->setActive($request->request->get('account_active'));
					$account->setColor($request->request->get('account_color'));
					$account->setTitle($request->request->get('account_title'));
						
					//return $viewHandler->handle($this->createErrorViewResponse($account));
					$errors = $validator->validate($account);
						
					if(count($errors) > 0){
						$return['errors'] = $errors;
							
						return $viewHandler->handle($this->createErrorViewResponse($return));
					} else {
						$em = $this->getDoctrine()->getEntityManager();
						$em->persist($account);
						$em->flush();
							
						$return['idAccount'] = $account->getId();
							
						return $viewHandler->handle($this->createSuccessViewResponse($return));
					}
					
					break;
				default:
					throw $this->createNotFoundException('Le type "'.$type.'" n\'existe pas');
					break;
			}
		} else {
			throw new MethodNotAllowedException('POST');
		}
	
	}
	
	public function deleteAccountAction($id)
	{
		$em = $this->getDoctrine()->getEntityManager();
		$viewHandler = $this->get('fos_rest.view_handler');
			
		$entity = $em->getRepository('IMTAccountBundle:Account')->find($id);
		
		$user = $this->get('security.context')->getToken()->getUser();
		
		if (!$entity) {
			throw $this->createNotFoundException('Le compte "'.$id.'" n\'existe pas');
		} else if($entity->getUser()->getId() != $user->getId()){
			throw $this->createNotFoundException('Le compte "'.$id.'" ne vous appartient pas');
		}
		
		$em->remove($entity);
		$em->flush();
		
		return $viewHandler->handle($this->createSuccessViewResponse(array('idAccount' => $id)));
	}
	
	private function createSuccessViewResponse($return)
	{
		$view = View::create()
		->setStatusCode(200)
		->setData($return);
	
		return $view;
	}
	
	private function createErrorViewResponse($return)
	{
		$view = View::create()
		->setStatusCode(Codes::HTTP_BAD_REQUEST)
		->setData($return);
	
		return $view;
	}
}